package com.carnation.servlet;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import com.carnation.service.Ftp;
import com.carnation.service.impl.FTPServerImpl;
import com.carnation.service.impl.SFTPServerImpl;
import com.carnation.utils.Json;
import com.carnation.utils.MenuFileUtril;
import com.google.gson.Gson;

public class DeleteRemoteFileServlet extends HttpServlet{

	private static final long serialVersionUID = 1L;
	private Logger logger = Logger.getLogger(DeleteRemoteFileServlet.class);

	@Override
	protected void doPost(HttpServletRequest httpServletRequest,HttpServletResponse httpServletResponse){
		String path = httpServletRequest.getParameter("path");
		String fileName = httpServletRequest.getParameter("filename");
		logger.info("path=" + path);
		logger.info("fileName = " + fileName);
		MenuFileUtril menuFileUtril = new MenuFileUtril();
		Ftp ftp = null;
		if(menuFileUtril.getFTPProtocol().toLowerCase().equals("ftp")){
			ftp = new FTPServerImpl();
		}
		else if(menuFileUtril.getFTPProtocol().toLowerCase().equals("sftp")){
			ftp = new SFTPServerImpl();
		}
		else{
			logger.info("未知协议类型");
		}
		if(ftp == null){
			return;
		}
		else{
			String msg = null;
			try {
				String realPath = ftp.getPath(path);
				String returnCode = ftp.deleteFile(realPath, fileName);
				if(returnCode.equals("200")){
					msg = "删除成功";
				}
				else if(returnCode.equals("304")){
					msg = "文件夹下还有文件或文件夹，不允许删除";
				}
				else if(returnCode.equals("404")){
					msg = "找不到对应文件，请向系统管理员反应";
				}
				else if(returnCode.equals("500")){
					msg = "系统发生异常，请与系统管理员联系";
				}
				else if(returnCode.equals("400")){
					msg = "删除失败";
				}
				else{
					msg = "未知返回码";
				}
				Json json = new Json();
				json.setMsg(msg);
				Gson gson = new Gson();
				httpServletResponse.setCharacterEncoding("UTF-8");
				httpServletResponse.getWriter().write(gson.toJson(json));
				httpServletResponse.getWriter().close();
			} catch (Exception e) {
				logger.error("获取真实路径出错",e);
			}
		}
	}
}
